import { ref } from 'vue'
import { showLoadingToast } from 'vant'
import dayjs from 'dayjs'

import { INDEX_ALL_TYPES } from '@/source/index'

import { sm2Decrypt } from '@/utils/sm2'
import { VantMessage } from '@/utils/vant-utils'

import { getList, deleteLive, collectLive } from '@/api/live'
import { getDemandList, collectDemand } from '@/api/demand'

export const useListCommon = () => {
  const page = ref(1)
  const total = ref(1)
  const list = ref([])

  let loadingToast = null

  //
  const getListData = (isLive, name, searchContext) => {
    return new Promise(async(resolve, reject) => {
      try {
        const current = INDEX_ALL_TYPES.find((item) => item.name === name)
        const params = {
          type: current.type,
          searchContext,
          pageNo: page.value,
          pageSize: 10
        }
        let listRes = {}

        if (isLive) {
          listRes = await getList(params)
        } else {
          listRes = await getDemandList(params)
        }
        if (listRes.data) {
          let currentList = listRes.data.records ? listRes.data.records : []
          total.value = listRes.data.total >= 0 ? listRes.data.total : 1
          if (isLive) {
            currentList = currentList.map((item) => {
              const startTime = item.startTime
              const endTime = item.endTime
              // TODO: 结束时间及密码
              return {
                ...item,
                startTime: dayjs(startTime).format('YYYY-MM-DD HH:mm'),
                meetingPassword: item.meetingPassword
                  ? sm2Decrypt(item.meetingPassword)
                  : '',
                startYmd: dayjs(startTime).format('YYYY年MM月DD日'),
                startHm: dayjs(startTime).format('HH:mm'),
                endYmd: dayjs(endTime).format('YYYY年MM月DD日'),
                endHm: dayjs(endTime).format('HH:mm')
              }
            })
          }
          resolve(currentList)
        } else {
          reject()
        }
      } catch (error) {
        reject(error)
      }
    })
  }

  // 移除
  const delListItem = async(id, name, cb) => {
    if (!loadingToast) {
      loadingToast = showLoadingToast({
        message: '删除中...',
        forbidClick: true,
        duration: 0
      })
    }
    try {
      if (name === 'live_my') {
        // 删除视频
        await deleteLive(id)
        VantMessage.success('删除成功')
      } else if (name === 'live_collect') {
        // 取消收藏
        await collectLive(id, true)
        VantMessage.success('取消收藏成功')
      } else if (name === 'video_collect') {
        // 取消点播收藏
        await collectDemand(id, true)
        VantMessage.success('取消收藏成功')
      }
      loadingToast.close()
      cb && cb()
    } catch (error) {
      loadingToast.close()
    }
  }

  return {
    page,
    total,
    list,
    delListItem,
    getListData
  }
}
